package freezzz.client;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import freezzz.client.EventWidget.EventWidget;
import freezzz.client.EventWidget.TimelineEvent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

class Slide extends Composite {
    private final Date date;

    private AbsolutePanel centerPanel;

    public Slide ( Date date ) {
        this.date = date;
        centerPanel = new AbsolutePanel ();

        FlowPanel flowPanel = new FlowPanel ();
        DateTimeFormat fmt = DateTimeFormat.getFormat ( "EEEE" );
        String dayOfTheWeek =  fmt.format ( date );
        fmt = DateTimeFormat.getFormat ( "MM.yyyy" );
        HTML title = new HTML( "<b>"+date.getDate ()+"</b>"+ fmt.format ( date )+"<br>"+dayOfTheWeek );
        title.setStyleName ( "slide-title" );


        flowPanel.add ( title );
        flowPanel.add ( centerPanel );

        initWidget ( flowPanel );
        setStyleName ( "slide" );
        fmt = DateTimeFormat.getFormat ( "dd.MM.yyyy" );
        if ( fmt.format ( date ).equals ( fmt.format ( new Date () ) ) ) {
            addStyleName ( "today" );
        }
        popupateSingleAjax ();


    }

    void populate ( ArrayList<TimelineEvent> timelineEventList ) {
        for ( TimelineEvent timelineEvent : timelineEventList ) {
            centerPanel.add ( new EventWidget ( timelineEvent ) );
        }
    }

    void popupateSingleAjax () {
        AsyncCallback<TimelineEvent[]> callback = new AsyncCallback<TimelineEvent[]>() {
            public void onFailure ( Throwable caught ) {

            }

            public void onSuccess ( TimelineEvent[] result ) {
                setAjaxLoading ( false );
                if ( result != null ) {
                    ArrayList<TimelineEvent> tmp = new ArrayList<TimelineEvent> ();
                    Collections.addAll ( tmp, result );
                    populate ( tmp );
                }
            }
        };
        setAjaxLoading ( true );
        TestService.App.getInstance ().getEventForDate ( date, callback );
    }

    void setAjaxLoading ( boolean value ) {
        if ( value ) {
            centerPanel.clear ();
            Image loading = new Image ( "res/static/ajax-loader.gif" );
            centerPanel.add ( loading );
        } else {
            centerPanel.clear ();
        }
    }
}
